package com.example.huixue.service;

import com.example.huixue.common.PageResult;
import com.example.huixue.entity.Comment;
import com.example.huixue.mapper.CommentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CommentService {
    
    @Autowired
    private CommentMapper commentMapper;
    
    /**
     * 添加评论
     */
    public Comment addComment(Long resourceId, Long userId, String content, Integer rating) {
        // 验证评论内容
        if (content == null || content.trim().isEmpty()) {
            throw new RuntimeException("评论内容不能为空");
        }
        
        // 验证评分（可选）
        if (rating != null && (rating < 1 || rating > 5)) {
            throw new RuntimeException("评分必须在1-5星之间");
        }
        
        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setResourceId(resourceId);
        comment.setContent(content.trim());
        comment.setRating(rating);
        comment.setCreatedAt(LocalDateTime.now());
        comment.setUpdatedAt(LocalDateTime.now());
        
        int result = commentMapper.insert(comment);
        if (result <= 0) {
            throw new RuntimeException("评论发表失败");
        }
        
        return comment;
    }
    
    /**
     * 更新评论
     */
    public Comment updateComment(Long commentId, String content) {
        Comment comment = commentMapper.findById(commentId);
        if (comment == null) {
            throw new RuntimeException("评论不存在");
        }
        
        // 验证评论内容
        if (content == null || content.trim().isEmpty()) {
            throw new RuntimeException("评论内容不能为空");
        }
        
        comment.setContent(content.trim());
        comment.setUpdatedAt(LocalDateTime.now());
        
        int result = commentMapper.update(comment);
        if (result <= 0) {
            throw new RuntimeException("评论更新失败");
        }
        
        return comment;
    }
    
    /**
     * 删除评论
     */
    public void deleteComment(Long commentId) {
        Comment comment = commentMapper.findById(commentId);
        if (comment == null) {
            throw new RuntimeException("评论不存在");
        }
        
        int result = commentMapper.deleteById(commentId);
        if (result <= 0) {
            throw new RuntimeException("评论删除失败");
        }
    }
    

    
    /**
     * 获取资源的评论列表（分页）
     */
    public PageResult<Comment> getResourceComments(Long resourceId, int current, int size) {
        int offset = (current - 1) * size;
        
        List<Comment> comments = commentMapper.findByResourceWithPagination(resourceId, offset, size);
        long total = commentMapper.countByResource(resourceId);
        
        return new PageResult<>(comments, total, current, size);
    }
    
    /**
     * 获取用户的评论列表（分页）
     */
    public PageResult<Comment> getUserComments(Long userId, int current, int size) {
        int offset = (current - 1) * size;
        
        List<Comment> comments = commentMapper.findByUserWithPagination(userId, offset, size);
        long total = commentMapper.countByUser(userId);
        
        return new PageResult<>(comments, total, current, size);
    }
    
    /**
     * 根据ID获取评论
     */
    public Comment getCommentById(Long commentId) {
        return commentMapper.findById(commentId);
    }
    
    /**
     * 获取最新评论
     */
    public List<Comment> getLatestComments(int limit) {
        return commentMapper.findLatestComments(limit);
    }
    
    /**
     * 获取资源评论数量
     */
    public long getResourceCommentCount(Long resourceId) {
        return commentMapper.countByResource(resourceId);
    }
    
    /**
     * 获取用户评论数量
     */
    public long getUserCommentCount(Long userId) {
        return commentMapper.countByUser(userId);
    }
    
    /**
     * 获取评论总数
     */
    public long getTotalCommentCount() {
        return commentMapper.countAll();
    }
    
    /**
     * 管理员获取所有评论列表（分页）
     */
    public PageResult<Comment> getAllCommentsWithPagination(int current, int size, String keyword) {
        int offset = (current - 1) * size;
        
        List<Comment> comments;
        long total;
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            comments = commentMapper.findAllWithKeywordPagination(keyword.trim(), offset, size);
            total = commentMapper.countAllWithKeyword(keyword.trim());
        } else {
            comments = commentMapper.findAllWithPagination(offset, size);
            total = commentMapper.countAll();
        }
        
        return new PageResult<>(comments, total, current, size);
    }
    
    /**
     * 批量删除评论
     */
    public void batchDeleteComments(List<Long> commentIds) {
        if (commentIds == null || commentIds.isEmpty()) {
            throw new RuntimeException("评论ID列表不能为空");
        }
        
        for (Long commentId : commentIds) {
            try {
                deleteComment(commentId);
            } catch (Exception e) {
                // 记录错误但继续删除其他评论
                System.err.println("删除评论失败: " + commentId + ", 错误: " + e.getMessage());
            }
        }
    }
} 